package com.adcc.ags.cgw.healthcheck;

import com.adcc.ags.cgw.configuration.GWFactory;
import com.adcc.ags.cgw.entity.mq.MQState;
import com.adcc.ags.cgw.entity.user.UserInfo;
import com.adcc.ags.cgw.proxy.UserProxy;
import com.adcc.utility.log.Log;
import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * 网关状态监控
 */
public class GWHealthCheck extends HealthCheck {

    // 网关配置
    private GWFactory gwFactory;

    /**
     * 构造函数
     * @param gwFactory
     */
    public GWHealthCheck(GWFactory gwFactory){
        this.gwFactory = gwFactory;
    }

    @Override
    protected Result check() throws Exception {
        try {
            Map<String,Object> map = Maps.newHashMap();

            // 设置网关名称
            map.put("name", gwFactory.getName());

            // 设置网关主机名称
            map.put("host", gwFactory.getHost());

            // 获取网关运行模式
            map.put("mode", UserProxy.getInstance().getGWMode());

            // 获取MQ运行状态
            Map<String,String> mq = Maps.newHashMap();
            mq.put("host", gwFactory.getMqFactory().getHost());
            mq.put("port",String.valueOf(gwFactory.getMqFactory().getPort()));
            mq.put("qm",gwFactory.getMqFactory().getQueueManager());
            mq.put("channel",gwFactory.getMqFactory().getChannel());
            mq.put("state", UserProxy.getInstance().getMqInfo().getState().toString());
            map.put("mq",mq);

            // 获取网关用户运行状态
            Map<String,UserInfo> gwUser = UserProxy.getInstance().getUserInfoMap();
            map.put("gwUser",gwUser.values());

            // 获取网关状态更新时间
            map.put("updateTime",UserProxy.getInstance().getMqInfo().getUpdateTime());
            if (UserProxy.getInstance().getMqInfo().getState() == MQState.CONNECTED) {
                return Result.healthy(new ObjectMapper().writeValueAsString(map));
            } else {
                return Result.unhealthy(new ObjectMapper().writeValueAsString(map));
            }
        } catch (Exception ex) {
            Log.error(GWHealthCheck.class.getName(), "check() error", ex);
            return Result.unhealthy(ex.toString());
        }
    }
}
